package com.boyinet.data.export.controller;

import com.boyinet.data.export.service.ExportDataService;
import com.boyinet.data.export.vo.SearchParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;


/**
 * @author lengchunyun
 */
@RestController
@RequestMapping("export")
public class ExportDataController {

    private final ExportDataService exportDataService;

    public ExportDataController(ExportDataService exportDataService) {
        this.exportDataService = exportDataService;
    }


    @PostMapping("file")
    public void file(@RequestBody SearchParam searchParam, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("History", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            exportDataService.export(response.getOutputStream(), searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("time")
    public void time(@RequestBody SearchParam searchParam, HttpServletResponse response) {
        try {
            exportDataService.exportByTime(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
